package com.ktjiaoyu.service.impl;

import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.mapper.SupplierMapper;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.utils.Page;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("supplierServiceImpl")
public class SupplierServiceImpl implements SupplierService {
    private static final Logger looger= LoggerFactory.getLogger(SupplierServiceImpl.class);




    @Resource
    private SupplierMapper supplierMapper;
    @Override
    public List<Supplier> getSupplierListByName(Supplier supplier) {
        return supplierMapper.getSupplierListByName(supplier);
    }
// 批量插入
    //Transactional 是一个事务注解，保证数据一致性
    @Transactional
    @Override
    public int insert(List<Supplier> supplierList) {
        int rows=0;
        for (int i = 0; i < supplierList.size(); i++) {
            //拿出每一条用户数据插入
            //抛出异常
            if (i==1){
                throw new RuntimeException("模拟数据库异常");
            }
            Supplier supplier=supplierList.get(i);
            rows+=supplierMapper.insert(supplier);
        }
        return rows;
    }

    @Override
    public int delete(Long id) {
        return supplierMapper.delete(id);
    }

    @Override
    public Page<Supplier> findPage(Integer offset, Integer pageSize) {
        Page<Supplier> page=null;
        try{
            page=new Page<Supplier>();
            page.setPageSize(pageSize);
            Long count= supplierMapper.count();
            page.setTotalPageCount( count.intValue());
            page.setPageNo(offset);
            //查询分页数据
            List<Supplier> data=supplierMapper.getPage(page.getPageNo(),page.getPageSize());
            page.setData(data);
        }catch (Exception e){
            looger.error("执行SysUserServiceImpl.findPage(SysUser,Integer,Integer)方法出现异常.", e);
            throw e;
        }
        return page;
    }

    @Override
    public boolean saveOrUpdate(Supplier supplier) throws Exception {
        try{
            if (supplier.getId()==null){
                //无主键 新增
                return supplierMapper.insert(supplier)>0;
            }else {
                //存在主键 修改
                return supplierMapper.update(supplier)>0;
            }
        }catch (Exception e){
            looger.error("执行SupplierServiceImpl.saveOrUpdate(Supplier)方法出现异常.", e);
            throw e;
        }
    }

    @Override
    public Supplier findBuId(Long id) throws  Exception{
        try{
            return supplierMapper.getById(id);
        }catch (Exception e){
            looger.error("执行SupplierServiceImpl.findBuId(Integer)方法出现异常.", e);
            throw e;
        }
    }
}
